File Handling

IO Streams and Files

 

Concept of IO Streams

 

Streams in Java

A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream because it is a continuous flow of data.

 

1.      Java treats flow of data as stream.

2.      Java streams are classified into two basic types: input stream and output stream.

3.      The java.io package contains a large number of stream classes to support the streams.

 

This package provides system input and output through data streams, serialization and the file system.

1.      Java I/O (Input and Output) is used to process the input and produce the output.

2.      Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the classes required for input and output operations.

3.      We can perform file handling in Java by java.io API.

Interfaces in Package java.io

 

Interface

Description

Closeable

A Closeable is a source or destination of data that can be closed.

DataInput

The DataInput interface provides for reading bytes from a binary stream and reconstructing from them data in any of the Java primitive types.

DataOutput

The DataOutput interface provides for converting data from any of the Java primitive types to a series of bytes and writing these bytes to a binary stream.

Externalizable

Only the identity of the class of an Externalizable instance is written in the serialization stream and it is the responsibility of the class to save and restore the contents of its instances.

FileFilter

A filter for abstract pathnames.

FilenameFilter

Instances of classes that implement this interface are used to filter filenames.

Flushable

A Flushable is a destination of data that can be flushed.

ObjectInput

ObjectInput extends the DataInput interface to include the reading of objects.

ObjectInputValidation

Callback interface to allow validation of objects within a graph.

ObjectOutput

ObjectOutput extends the DataOutput interface to include writing of objects.

ObjectStreamConstants

Constants written into the Object Serialization Stream.

Serializable

Serializability of a class is enabled by the class implementing the java.io.Serializable interface.

 

Exceptions in Package java.io

 

 

I-O stream classes in Java

Java provides java.io package which contains a large number of stream classes to process all types of data:

Ø  Byte stream classes

        Support for handling I/O operations on bytes

Ø  Character stream classes

        Supports for handling I/O operations on characters 

 

 

Methods in Byte Stream (input) classes

Method

Description

read( )

Read a byte from the input stream

read(byte b[ ])

Read an array of bytes into b

read(byte b[ ], int n, int m)

Reads m bytes into b starting from nth  byte

available( )

Gives number of bytes available in the input

skip(n)

Skips over n bytes from the input stream

reset( )

Goes back to the beginning of the stream

close( )

Close the input steam

 

Example: 

DataInputStream

readShort( )

readDouble( )

readInt( )

readLine( )

readLong( )

readChar( )

readFloat( )

readBoolean( )

readUTF( )

 

Methods in Byte Stream (output) classes

Method

Description

write (int b )

Write a byte from the input stream

write (byte b[ ])

Write all bytes in the array b to the output steam

write (byte b[ ], int n, int m)

Write m bytes from array b starting from nth  byte

close( )

Close the output stream

flush( )

Flushes the output stream

 

Example: 

DataOutputStream

writeShort( )

writeDouble( )

writeInt( )

writeLine( )

writeLong( )

writeChar( )

writeFloat( )

WriteBoolean( )

writeUTF( )

 

 

Methods in Character Stream (reader) classes

Method

Description

close()

Closes the stream and releases any system resources associated with it.

mark(int readAheadLimit)

Tells whether this stream supports the mark() operation.

markSupported()

Tells whether this stream supports the mark() operation.

read()

Reads a single character.

read(char[] cbuf)

Reads characters into an array.

read(char[] cbuf, int off, int len)

Reads characters into a portion of an array.

read(CharBuffer target)

Attempts to read characters into the specified character buffer.

ready()

Tells whether this stream is ready to be read.

reset()

Resets the stream.

skip(long n)

Skips characters.

 

Methods in Character Stream (Writer) classes

Method

Description

append(char c)

Appends the specified character to this writer.

append(CharSequence csq)

Appends the specified character sequence to this writer.

append(CharSequence csq, int start, int end)

Appends a subsequence of the specified character sequence to this writer.

close()

Closes the stream, flushing it first.

flush()

Flushes the stream.

write(char[] cbuf)

Writes an array of characters.

write(char[] cbuf, int off, int len)

Writes a portion of an array of characters.

write(int c)

Writes a single character.

write(String str)

Writes a string.

write(String str, int off, int len)

Writes a portion of a string.

 

IO with Byte Streams

 

Byte Stream Classes are used to read bytes from an input stream and write bytes to an output stream.

Working of byte stream class

 

Byte Stream classes are divided in two groups:

        InputStream classes: These classes are subclasses of an abstract class InputStream and they are used to read bytes from a source (file, memory, or console).

        OutputStream classes: These classes are subclasses of an abstract class OutputStream and they are used to write bytes to a destination (file, memory or console).

Notes:

        Programs use byte streams to perform input and output of 8-bit bytes.

        All byte stream classes are descended from InputStream and OutputStream.

        There are many byte stream classes. To demonstrate how byte streams work, we'll focus on the file I/O byte streams, FileInputStream and FileOutputStream.

        Other kinds of byte streams are used in much the same way; they differ mainly in the way they are constructed.

 

Java Input Stream Classes

 

 

 

Note:

InputStream class is an abstract class. It is the superclass of all classes representing an input stream of bytes.

public abstract class InputStream extends Object implements Closeable

 

Classes under InputStream class

Class

Description

BufferedInputStream

A BufferedInputStream adds functionality to another input stream-namely, the ability to buffer the input and to support the mark and reset methods.

ByteArrayInputStream

A ByteArrayInputStream contains an internal buffer that contains bytes that may be read from the stream.

DataInputStream

A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way.

FileInputStream

A FileInputStream obtains input bytes from a file in a file system.

PipedInputStream

A piped input stream should be connected to a piped output stream; the piped input stream then provides whatever data bytes are written to the piped output stream.

ObjectInputStream

An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream.

 

available()

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

close()

Closes this input stream and releases any system resources associated with the stream.

mark(int readlimit)

Marks the current position in this input stream.

markSupported()

Tests if this input stream supports the mark and reset methods.

read()

Reads the next byte of data from the input stream.

read(byte[] b)

Reads some number of bytes from the input stream and stores them into the buffer array b.

read(byte[] b, int off, int len)

Reads up to len bytes of data from the input stream into an array of bytes.

reset()

Repositions this stream to the position at the time the mark method was last called on this input stream.

skip(long n)

Skips over and discards n bytes of data from this input stream.

 

InputStream classes is used to read 8-bit bytes and supports a number of input-related methods

        Reading bytes

        Closing streams

        Marking positions in streams

        Skipping ahead in streams

        Finding the number of bytes in stream

        and many more…

 

Some input stream methods

DataInputStream

readShort( )

readDouble( )

readInt( )

readLine( )

readLong( )

readChar( )

readFloat( )

readBoolean( )

readUTF( )

 

Reading from Keyboard

Example 43.1: Reading String, Integer and Double from Keyboard

Text Box: import java.io.*;
public class KeyboardReading{
    public static void main(String args[]) throws IOException {
  	DataInputStream dis = new DataInputStream(System.in);
     System.out.println("Enter a String: ");
  	String str1 = dis.readLine();
  	System.out.println("Entered String value is: " + str1);
  	System.out.println("Enter a whole number: ");
  	String str2 = dis.readLine();
  	int x = Integer.parseInt(str2);
  	System.out.println("Enter a double value: ");
  	String str3 = dis.readLine();
  	double y = Double.parseDouble(str3);
  	if(x > y)
    	    System.out.println("First number " +x + " is greater than second number " + y);
          else
              System.out.println("First number " +x + " is less than second number " + y);
          dis.close();
     }
}

Example 43.2: Calculator using DataInputStream

Text Box: import java.io.*;
class InterestCalculator   {
   public static void main(String args[ ] )   {
   Float principalAmount = new Float(0);
   Float rateOfInterest = new Float(0);
   int numberOfYears = 0;
   
   DataInputStream in = new DataInputStream(System.in);
   String tempString;  
   System.out.print("Enter Principal Amount: ");
   System.out.flush();
   tempString = in.readLine();
   principalAmount = Float.valueOf(tempString);
  System.out.print("Enter Rate of Interest: ");
  System.out.flush();
  tempString = in.readLine();
  rateOfInterest = Float.valueOf(tempString);
  System.out.print("Enter Number of Years:");
  System.out.flush();   
  tempString = in.readLine();
  numberOfYears =   Integer.parseInt(tempString);
  // Input is over: calculate the interest
  int interestTotal =   principalAmount*rateOfInterest*numberOfYears;
  System.out.println("Total Interest = " +   interestTotal);
    }
 }


Example 43.3: Reading bytes from a file and display data

Text Box: // Read the file address from the Command Line
import java.io.*; 
class ReadBytesDemo {
   public static void main (String args[])  { 
  FileInputStream infile = null; // Create an input file stream 
  int b; 
  try  { 
     infile = new FileInputStream(args[0]); 
    // Connect infile stream to the required file 
     while((b = infile.read()) != -1)  { 
             System.out.print((char)b); // Read and display data 
     } 
     infile.close(); 
  } 
  catch(IOException ioe)  { 
    System.out.println(ioe); 
  }
   }
}

Example 43.4: Using methods of the FileInputStream class

Text Box: class InputStreamTest   {
 public static void main (String args [ ] ) {
  int size;
  
  // To open a file input stream.
  FileInputStream fin;
  fin = new FileInputStream (" C:\WINDOWS\SYSTEM\SYSTEM.INI");
  size = fin.available( );  
  
  // returns the number of bytes available
  System.out.println("Total bytes ::" + size);
  System.out.println ( " First ¼ is displayed : Using read( )");
  
  for (int i = 0; i < size /4 ; i++ ) {
      System.out.println ((char) fin.read( ) );
  }
    System.out.println (" Remaining bytes :" + fin.available( ) );
    System.out.println ("Next ¼ is displayed : Using read( b[ ])");
    byte b[] = new byte[size/4];
    if (fin.read (b) != b.length ) 
           System.err.println ("File reading error : ");
    else {
      String temp = new String (b, 0, 0, b.length );  
      // Convert the bytes into string
      System.out.println (temp) ;    
      // display text string.
      System.out.println (" Still available:"+fin.available( ) );
      System.out.println (" skipping ¼ : Using skip ( )" );
      fin.skip(size/4); 
      System.out.println (" File remaining for read ::"+fin.available( ) );
    }  
    fin.close ( );   // Close the input stream
  } 
}

 

Byte Output Stream Classes

 

Hierarchy of OutputStream

 

 

 

OutputStream class is an abstract class. It is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink.

public abstract class OutputStream extends Object implements Closeable, Flushable

 

OutputStream classes

Class

Description

BufferedOutputStream

The class implements a buffered output stream.

ByteArrayOutputStream

This class implements an output stream in which the data is written into a byte array.

DataOutputStream

A data output stream lets an application write primitive Java data types to an output stream in a portable way.

FileOutputStream

A file output stream is an output stream for writing data to a File or to a FileDescriptor.

ObjectOutputStream

An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream.

 

Use of class OutputStream

Methods of OutputStream class 

Method

Description

close()

Closes this output stream and releases any system resources associated with this stream.

flush()

Flushes this output stream and forces any buffered output bytes to be written out.

write(byte[] b)

Writes b.length bytes from the specified byte array to this output stream.

write(byte[] b, int off, int len)

Writes len bytes from the specified byte array starting at offset off to this output stream.

write(int b)

Writes the specified byte to this output stream.

 

OutputStream classes is used to write 8-bit bytes and supports a number of input-related methods

        Writing bytes

        Closing streams

        Flushing streams

        etc.

 

DataOutputStream

writeShort( )

writeDouble( )

writeInt( )

writeLine( )

writeLong( )

writeChar( )

writeFloat( )

WriteBoolean( )

writeUTF( )

 

Example 43.5: Storing data into a File

Text Box: import java.io.*; 
class ReadWritePrimitive{ 
   public static void main (String args[]) throws IOException{ 
     
     File primitive = new File("prim.dat");
     FileOutputStream fos = new FileOutputStream(primitive);
     DataOutputStream dos = new DataOutputStream(fos);
    
     //Write primitive data to the "prim.dat"file
     dos.WriteInt(1999);
     dos.WriteDouble(375.85);
     dos.WriteBoolean(false);
     dos.WriteChar('X');
      dos.close();
      fos.close();
      //Read data from the "prim.dat" file
      FileInputStream fis = new FileInputStream(primitive);
      DataInputStream dis = new DataInputStream(fis);
      System.out.println(dis.ReadInt());
      System.out.println(dis.ReadDouble());
      System.out.println(dis.ReadBoolean());
      System.out.println(dis.ReadChar());
      
      dis.close();
      fis.close();
   }
}

Example 43.6: Copying bytes from one file to another

Text Box: import java.io.*; 
class CopyBytes{ 
  public static void main (String args[])  { 
  
  //Declare input and output file streams 
  FilelnputStream infile = null;     
  
  //Input stream       
  FileOutputStream outfile = null;        
  
  //Output stream 
  //Declare a variable to hold a byte 
  byte byteRead; 
try  { 
     //Connect infile to in.dat 
     infile = new FilelnputStream("in.dat");
 
     //Connect outfile to out.dat 
     outfile = new FileOutputStream("out.dat");
 
     //Reading bytes from in.dat and writing to out.dat 
     do  { 
       byteRead = (byte) infile.read()
       outfile.write(byteRea  d); 
     }
  while(byteRead != -  1); 
}
catch(FileNotFoundException e) { 
      System.out.println("File not 
      found"); 
    }
    catch(IOException e) { 
      System.out.println(e. 
      getMessage()); 
    }
   finally   //Close files 
   { 
        try {
        infile.close();
        outfile.close();
   }
        catch(IOException e){}
    }
  }
}

 

Note:

        Closing a stream when it's no longer needed is very important.

        Always make sure that each stream variable contains an object reference before invoking close.

        Using Bytes is a kind of low-level I/O that should be avoided. Since for character data, the best approach is to use character streams. There are also streams for more complicated data types.

        Byte streams should only be used for the most primitive I/O.

        All other stream types are built on byte streams.

 

IO with Character Streams

 

Character Stream Classes

        In Western locales, the local character set is usually an 8-bit superset of ASCII.

        The Java platform stores character values using Unicode conventions.

        Character stream I/O automatically translates this internal format to and from the local character set.

 

Taxonomy: Java stream classes

 

 

Character stream  classes is used to read and write characters and supports a number of input-output related methods

Ø  Reader stream classes

        To read characters from files.

        In many way, identical to InputStream classes.

Ø  Writer stream classes

        To write characters into files.

        In many way, identical to OutputStream classes.

 

Reader Stream Classes

 

 

        Abstract class for reading character streams.

public abstract class Reader extends Object implements Readable, Closeable

        The only methods that a sub class must implement are read(char[], int, int) and close().

        Most sub classes, however, will override some of the methods defined here in order to provide higher efficiency, additional functionality, or both.

 

Different classes under the Reader class

Method

Description

BufferedReader

Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

CharArrayReader

This class implements a character buffer that can be used as a character-input stream.

InputStreamReader

An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset.

PipedReader

Piped character-input streams.

FilterReader

Abstract class for reading filtered character streams.

PushbackReader

A character-stream reader that allows characters to be pushed back into the stream.

StringReader

A character stream whose source is a string.

LineNumberReader

A buffered character-input stream that keeps track of line numbers.

FileReader

Convenience class for reading character files.

 

Constructors and Fields in Reader class

Fields

Field

Description

protected Object lock

The object used to synchronize operations on this stream.

 

Constructor

Description

Reader()

Creates a new character-stream reader whose critical sections will synchronize on the reader itself.

Reader(Object lock)

Creates a new character-stream reader whose critical sections will synchronize on the given object.

 

Methods in Reader class

Method

Description

close()

Closes the stream and releases any system resources associated with it.

mark(int readAheadLimit)

Tells whether this stream supports the mark() operation.

markSupported()

Tells whether this stream supports the mark() operation.

read()

Reads a single character.

read(char[] cbuf)

Reads characters into an array.

read(char[] cbuf, int off, int len)

Reads characters into a portion of an array.

read(CharBuffer target)

Attempts to read characters into the specified character buffer.

ready()

Tells whether this stream is ready to be read.

reset()

Resets the stream.

skip(long n)

Skips characters.

 

Example 44.1: Reading String, Integer and Double from Keyboard

Text Box: import java.io.*;
public class KeyboardReading{
  public static void main(String args[]) throws IOException {
    BufferedReader b = new BufferedReader(new InputStreamReader(System.in));	
    System.out.println("Enter a String: ");
    String str1 = b.readLine();
    System.out.println("Entered String value is: " + str1);
 
    System.out.println("Enter a whole number: ");
    String str2 = b.readLine();
    int x = Integer.parseInt(str2);
 
    System.out.println("Enter a double value: ");
    String str3 = b.readLine();
    double y = Double.parseDouble(str3);
 
    if(x > y)
      System.out.println("First number " +x + " is greater than second number " + y);
    else
      System.out.println("First number " +x + " is less than second number " + y);
 
    b.close();
  }
}

Example 44.2: Calculator using BufferedReader

Text Box: import java.io.*;
class InterestCalculator   {
   public static void main(String args[ ] ) throws IOException {
   Float principalAmount = new Float(0);
   Float rateOfInterest = new Float(0);
   int numberOfYears = 0;
   
   BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
   String tempString;  
   System.out.print("Enter Principal Amount: ");
   System.out.flush();
   tempString = b.readLine();
   principalAmount = Float.valueOf(tempString);
   System.out.print("Enter Rate of Interest: ");
   System.out.flush();
  tempString = b.readLine();
  rateOfInterest = Float.valueOf(tempString);
  System.out.print("Enter Number of Years:");
  System.out.flush();   
  tempString = b.readLine();
  numberOfYears =   Integer.parseInt(tempString);
  // Input is over: calculate the interest
  int interestTotal =   principalAmount*rateOfInterest*numberOfYears;
  System.out.println("Total Interest = " +   interestTotal);
    }
 }

Writer Stream Classes

 

        Abstract class for writing character streams.

           public abstract class Writer extends Object implements Appendable, Closeable, Flushable

        The only methods that a subclass must implement are write(char[], int, int), flush(), and close().

        Most subclasses, however, will override some of the methods defined here in order to provide higher efficiency, additional functionality, or both.

 

Sub classes of the Writer class

Class

Description

BufferedWriter

Writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

CharArrayWriter

This class implements a character buffer that can be used as an Writer.

PipedWriter

Piped character-output streams.

StringWriter

A character stream that collects its output in a string buffer, which can then be used to construct a string.

FileWriter

Convenience class for writing character files.

FilterWriter

Abstract class for writing filtered character streams.

PrintWriter

Prints formatted representations of objects to a text-output stream.

 

Constructors and Fieldsin Writer class

Fields

Field

Description

protected Object lock

The object used to synchronize operations on this stream.

 

Constructor

Description

Writer()

Creates a new character-stream writer whose critical sections will synchronize on the writer itself.

Writer(Object lock)

Creates a new character-stream writer whose critical sections will synchronize on the given object.

 

Example 44.3: Copying files using FileReader and FileWriter

Text Box: import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CopyChars {
  public static void main(String[] args) throws IOException {
   FileReader inputStream = null;
   FileWriter outputStream = null;
   try {
     inputStream = new FileReader("nptel.txt");
     outputStream = new FileWriter("characteroutput.txt");
     int c;
     while ((c = inputStream.read()) != -1) {
      outputStream.write(c);
     }
   } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }
}

CopChars versus CopyBytes

        CopyChars is very similar to CopyBytes. The most important difference is that CopyChars uses FileReader and FileWriter for input and output in place of FileInputStream and FileOutputStream.

        Both CopyBytes and CopyChars use an int variable to read to and write from.

        In CopyChars, the int variable holds a character value in its last 16 bits;

        In CopyBytes, the int variable holds a byte value in its last 8 bits.

Summary of Java Streams: List of important tasks and their classes

Task

Character Stream Class

Byte Stream Class

Performing input operations

Buffering input

Keeping track of line numbers

Reading from an array

Translating byte stream into a character stream

Reading from files

Filtering the input

Pushing back characters/bytes

Reading from a pipe

Reading from a string

Reading primitive types

Performing output operations

Buffering output

Writing to an array

Filtering the output

Translating character stream into a byte stream

Writing to a file

Printing values and objects

Writing to a pipe

Writing to a string

Writing primitive types

Reader

BufferedReader

LineNumberReader

CharArrayReader

InputStreamReader

FileReader

FilterReader

PushbackReader

PipedReader

StringReader

(none)

Writer

BufferedWriter

CharArrayWriter

FilterWriter

OutputStreamWriter

FileWriter

PrintWriter

PipedWriter

StringWriter

(none)

InputStream

BufferedlnputStream

LineNumberlnputStream

ByteArrayInputStream

(none)

FileInputStream

FilterlnputStream

PushbackInputStream

PipedInputStream

StringBufferInputStream

DataInputStream

OutputStream

BufferedOutputStream

ByteArrayOutputStream

FilterOutputStream

(none)

FileOutputStream

PrintStream

PipedOutputStream

(none)

DataOutputStream

le Input-Output

Java File I/O

Java provides java.io package which includes numerous class definitions and methods to manipulate file and flow of data (called File I/O streams)

There are four major classes:

        File

        FileInputStream

        FileOutputStream

        RandomAccessFile

 

Using class File

Using class File

 

Example 45.1: Knowing information about a File object

Text Box: import java.io.File     
class FileTest  {
      public static void main (String args [ ] ) throws IOException {
        	File  fileToCheck;
  	if (args.length > 0 ) {
     	    for (int i = 0; i < args.length;i++ ) {
              	fileToCheck = new File(args[ i ]);
              	getPaths(fileToCheck);
              	getInfo(fileToCheck);
            }   
  	}
  	else 
       	   System.out.println (" Usage : Java FileTest <filename (s) >);   
    }
    public static void getPaths (File f ) throws IOException {
  	  System.out.println ("Name : " + f. getName( ) );
  	  System.out.println ("Path : " + f. getPath ( ) );
  	  System.out.println ("Parent : " + f.getParent ( ) );
     }
     public static void getInfo (File f ) throws IOException  {
  	if (f.exists ) {
      	     System.out.print ("File exists ");
      	     System.out.println (f.canRead( ) ? "and is readable" : "");
              System.out.println ( f.canWrite( ) ? "and is writable" : "");
              System.out.println ("File is last modified : + f.lastModified( ));
              System.out.println ("File is " + f.length( ) + "bytes" );
  	}
  	else 
      	     System.err.println (" File does not exist." );
     } 
}

Example 45.2: Storing and reading data in the same file

Text Box: import java.io.*;
class ReadWriteIntegers{  
    public static void main (String args[]) {
        DatalnputStream dis = null;    //Input stream 
        DataOutputStream dos = null;   //Output stream 
   
        File intFile = new File("rand.dat");       
	//Construct a file 
	//Writing integers to rand.dat file 
	try {    //Create output stream for intFile file 
	     dos = new DataOutputStream(new FileOutputStream(intFile));
  	     for(int i=0;i<20;i++) 
    	         dos.writelnt ((int)(Math. random () *100)); 
	} 
	catch(IOException ioe)     { 
  	     System.out.println(ioe.getMessage()); 
	} 
  	finally  {       
    	 dos.close()
          }       
     }
	//Reading integers from rand.dat file 
	try { 
    	    //Create input stream for intFile file
              dis = new DatalnputStream(new   FilelnputStream(intFile));    
                 
   	     for(int i=0;i<20;i++) { 
    		int n = dis.readlnt(); 
    		System.out.print(n + " "); }   
 	     }
  	catch(IOException ioe) {
   	     System.out.println(ioe.getMessage());
   	}
   	finally {
             dis.close();
          }    
      }
  }

Example 45.3: Concatenation and buffering

Text Box: import java.io.*; 
class MergeFilesDemo{
  public static void main (String args[]) throws   IOException{
  //Declare file streams 
  FilelnputStream file1 = null; 
  FilelnputStream file2 = null;      
  SequencelnputStream file3 = null;   
  //Declare file3 to store combined files 
  file1 = new FilelnputStream("text1.dat");   //Open the files to be concatenated 
  file2 = new FilelnputStream("text2.dat");   //Open the files to be concatenated 
  file3 = new SequencelnputStream(filel,file2) ;   //Concatenate filel and file2
  //Create buffered input and output streams 
  BufferedlnputStream inBuffer = new   BufferedlnputStream(file3);
BufferedOutputStream outBuffer = new   BufferedOutputStream(System.out);
//Read and write till the end of buffers 
  int ch; 
  while((ch = inBuffer.read()) != -1)      
outBuffer.write((char)ch);
inBuffer.close();
outBuffer.close();
file1.close();
file2.close();
   }
}

Example 45.4: Interactive input and output

Text Box: import java. util. *; // To use StringTokenizer class 
import java.io.*;
 
class Inventory { 
    static DataInputStream din = new DataInputStream(System.in); 
    static StringTokenizer st; 
    public static void main (String args[J) throws IOException{
    	DataOutputStream dos = new DataOutputStream(new FileOutputStream("invent.dat")); 
    	// Reading from console 
    System.out.println("Enter code number"); 
    st = new StringTokenizer(din.readLine()); 
    int code = Integer.parseInt(st.nextToken()); 
    System.out.println("Enter number of items"); 
    st = new StringTokenizer(din.readLine()); 
    int items = Integer.parselnt(st.nextToken()); 
    System.out.println("Enter cost"); 
    st = new StringTokenizer(din.readLine()); 
    double cost = new Double(st.nextToken()).doubleValue{};
	// Writing to the file "invent.dat" 
    dos.writeInt(code); 
    dos.writeInt(items); 
    dos.writeDouble(cost); 
    dos.close(); 
    	// Processing data from the file 
    DataInputStream dis = new DataInputStream(new FileInputStream("invent.dat")); 
    int codeNumber = dis.readInt(); 
    int totalItems = dis.readInt(); 
    double itemCost = dis.readDouble(); 
    double totalCost = total Items * itemCost; 
    dis.close(); 
    // Writing to console 
    System.out.println(); 
    System.out.println("Code Number : " + codeNumber); 
    System.out.println("Item Cost : " + itemCost); 
    System.out.println("Total Items : " + totalItems);  
    System.out.println("Total Cost  : " + totalCost); 
    }
}

Graphical input and output

 

Example 45.5: Graphical input and output

Text Box: import java.io.*; 
import java.awt.*; 
class StudentFile extends Frame {
    // Defining window components 
    TextField number, name, marks; 
    Button enter, done; 
    Label numLabel, nameLabel, markLabel; 
    DataOutputStream dos;
    
    // Initialize the Frame 
    public StudentFile(){ 
        super("Create Student File"); 
    }
    // Setup the window 
    public void setup() { 
        resize(400, 200); 
        setLayout(new GridLayout(4,2));
    // Create the components of the Frame
    number = new TextField(25);
    number = new TextField(25); 
    numLabel = new Label("Roll Number"); 
    name = new TextField(25); 
    nameLabel = new Label ("Student Name"); 
    marks = new TextField(25); 
    markLabel = new Label("Marks"); 
    enter = new Button("ENTER"); 
    done = new Button("DONE");
    // Add the components to the Frame 
    add(numLabel); 
    add(number); 
    add(nameLabel); 
    add(name); 
    add(markLabel); 
    add(marks); 
    add(enter); 
    add(done);        
    // Show the Frame 
    show();
// Open the file 
    try    { 
    dos new DataOutputStream( new     FileOutputStream("student.dat"));
    } 
    catch(IOException e)     {         
        System.err.println(e.toString()); 
         System.exit(1); 
    }
  }
  // Write to the file 
  public void addRecord()    { 
 int num; 
 Double d; 
 num = (new Integer(number.getText())).intValue(); 
      try {
dos.writelnt(num); 
dos.writeUTF(name.getText()); 
d = new Double(marks.getText()); 
dos.writeDouble(d.doubleValue());
      }
         catch(IOException e) { }
    // Clear the text fields 
    number.setText(" "); 
    name.setText(" "); 
    marks.setText(" "); 
    }
     // Adding the record and clearing the TextFields 
    public void cleanup()    {
        if(!number.getText(). equals(" ")) { 
             addRecord(); 
        } 
        try { 
             dos.flush();
             dos.close(); 
        } 
        catch(IOException e) { } 
    }
	// Processing the event 
	public boolean action(Event event,Object o) { 
    	     if(event.target instanceof Button) 
    		if(event.arg.equals("ENTER")) { 
         	     addRecord(); 
         	     return true;
                   }
    		return super.action(event, o); 
        	}
    public boolean handleEvent(Event event) {
	if(event.target instanceof Button)            		    if(event.arg.equals("DONE")) { 
                 cleanup();                       
        	        System.exit(0); 
                 return true;
    	    }
    	    return super.handleEvent(event); 
   	 }    
     // Execute the program 
    public static void main (String args[]) { 
    StudentFile student = new StudentFile();
         student.setup();
    }
}

Random Access File

Taxonomy of RandomAccessFile class

 

This class is used for reading and writing to random access file.

        A random access file behaves like a large array of bytes.

        There is a cursor implied to the array called file pointer, by moving the cursor we do the read write operations.

        If end-of-file is reached before the desired number of byte has been read than EOFException is thrown. It is a type of IOException.

Constructors of RandomAccessFile class

Constructor

Description

RandomAccessFile(File file, String mode)

Creates a random access file stream to read from, and optionally to write to, the file specified by the File argument.

RandomAccessFile(String name, String mode)

Creates a random access file stream to read from, and optionally to write to, a file with the specified name.

 

Methods of RandomAccessFile class

Method

Description

close()

It closes this random access file stream and releases any system resources associated with the stream.

getChannel()

It returns the unique FileChannel object associated with this file.

readInt()

It reads a signed 32-bit integer from this file.

readUTF()

It reads in a string from this file.

seek(long pos)

It sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.

writeDouble(double v)

It converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that long value to the file as an eight-byte quantity, high byte first.

writeFloat(float v)

It converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the file as a four-byte quantity, high byte first.

write(int b)

It writes the specified byte to this file.

read()

It reads a byte of data from this file.

length()

It returns the length of this file.

seek(long pos)

It sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.

 

Usefulness of class RandomAccessFile

        As the name implies the class RandomAccessFile allows us to handle a file randomly in contrast to sequentially in InputStream or OutputStream classes.

        It allows to move file pointer randomly.

        Moreover, it allows read or write or read-write simultaneously.

 

Reading from a RAF

Methods used to read RAF

Method

Description

read()

It reads a byte of data from this file.

length()

It returns the length of this file.

seek(long pos)

It sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.

close()

It closes this random access file stream and releases any system resources associated with the stream.

getChannel()

It returns the unique FileChannel object associated with this file.

readInt()

It reads a signed 32-bit integer from this file.

readUTF()

It reads in a string from this file.

 

Example 46.1: Reading from a RAF

Text Box: import java.io.IOException;  
import java.io.RandomAccessFile;  
  
public class RandomAccessFileExample {  
    static final String FILEPATH ="NPTEL.txt";  
    public static void main(String[] args) {  
        try {  
            System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
    private static byte[] readFromFile(String filePath, int position, int size)  
            throws IOException {  
        RandomAccessFile file = new RandomAccessFile(filePath, "r");  
        file.seek(position);  
        byte[] bytes = new byte[size];  
        file.read(bytes);  
        file.close();  
        return bytes;  
    }
}

Writing into a RAF

Methods to write into RAF

Method

Description

write(int b)

It writes the specified byte to this file.

length()

It returns the length of this file.

seek(long pos)

It sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.

close()

It closes this random access file stream and releases any system resources associated with the stream.

writeDouble(double v)

It converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that long value to the file as an eight-byte quantity, high byte first.

writeFloat(float v)

It converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the file as a four-byte quantity, high byte first.

write(int b)

It writes the specified byte to this file.

 

Example 46.2: Writing into a RAF

Text Box: import java.io.IOException;  
import java.io.RandomAccessFile;  
  
public class RandomAccessFileExample {  
    static final String FILEPATH ="myFile.TXT";  
    public static void main(String[] args) {  
        try {
            writeToFile(FILEPATH, "Data Structures and Algorithms Using Java", 41);  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    } 
    private static void writeToFile(String filePath, String data, int position)  
        throws IOException {  
        RandomAccessFile file = new RandomAccessFile(filePath, "rw");  
        file.seek(position);  
        file.write(data.getBytes());  
        file.close();  
    }  
}

Example 46.3: Reading and writing RAF

Text Box: import java.io.*; 
class RandomIO{
  public static void main (String args[)){ 
     RandomAccessFile file = null; 
     try { 
      file = new             
      RandomAccessFile("rand.dat","rw");
      // Writing to the file 
      file.writeChar('X'); 
      file.writelnt(555); 
      file.writeDouble(3.1412); 
      file.seek (0); 
      // Go to the beginning 
      // Reading from the file 
      System.out.println(file.readChar());
    System.out.println(file.readlnt()); 
    System.out.println(file.readDouble()); 
    file.seek(2); // Go to the second item 
    System.out.println(file.readlnt()); 
    // Go to the end and append false to the file 
    file.seek(file.length()); 
    file.writeBoolean(false); 
    file. seek (4) ; 
    System.out.println(file.readBoolean()); 
    file.close(); 
    } 
    catch(IOException e)
    {
    	System.out.println(e);
    }
  }
}

Example 46.4: Appending to a RAF

Text Box: import java.io.*;
class RandomAccess {
  static public void main(String args[]){
    RandomAccessFile rFile;
    try{
    	rFile = new RandomAccessFile("city.txt","rw");    
    	rFile.seek(rFile.lenght());  	// Go to the end
    	rFile.writeByte(“Joy with Java\n"); //Append MUMBAI	
    	rFile.close();
    }
    catch(IOException ioe){
    	System.out.println(ioe);
    }
  }
}

Example 46.4: Appending to a RAF                                                      

Consider the Student class for both Read and Write Operations.

Text Box: import java.io.Serializable;
import java.util.*; 
 
public class Student implements Serializable {
    //default serialVersion id
    private static final long serialVersionUID = 1L;
    private String firstName;
    private String lasName;
    private int age;
    private int marks[] =  new int[5];
 
    public Student(String fname, String lname, int age, int smarks[]){
        this.firstName = fname;
        this.lastName  = lname;
        this.age        = age;
        this.marks	    = smarks;
    }
 
    public void setFirstName(String fname) {
        this.firstName = fname;
    }
    public String getFirstName() {
        return this.firstName;
    }
    
    public void setLastName(String lname) {
        this.firstName = lname;
    }
 
    public String getLastName() {
        return this.lastName;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public int getAge() {
        return this.age;
    }
    public void setMarks(int smarks[]) {
        this.marks = smarks;
    }
 
    public int[] getMarks() {
        return this.marks;
    } 
    
    @Override
    public String toString() {
        return new StringBuffer(" \nFirst Name: ").append(this.first_name)
                .append(" \nLast Name : ").append(this.last_name)
                .append(" \nAge : ").append(this.age)
                .append(" \nMarks : ")
                .append(Arrays.toString(this.marks)).toString();
    }
}

Example 46.5: Reading and writing objects (create objects and writing)

Text Box: import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
 
public class WriteObjectDemo{
    private static final String filepath="D:\\Java\\obj";
                    public static void main(String args[]) {
        WriteObject objectIO = new ObjectIO();
        int m[] = {50,47,89,65,78};
        Student student = new Student("John","Frost",22,m);
        objectIO.writeObjectToFile(student);
        }
 
        public void writeObjectToFile(Object serObj) {
        try {
            FileOutputStream fileOut = new FileOutputStream(filepath);
            ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
            objectOut.writeObject(serObj);
            objectOut.close();
            System.out.println("The Object  is successfully written to a file");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Example 46.6: Reading and writing objects (reading objects from file)

Text Box: import java.io.FileInputStream;
import java.io.ObjectInputStream;
 
public class ReadObjectDemo{
    private static final String filepath="D:\\Java\\obj";
    public static void main(String args[]) {
        ReadObject objectIO = new ReadObject();
        objectIO.readObjectFromFile();
    }
    public void readObjectFromFile() {
        try {
            FileInputStream fileIn = new FileInputStream(filepath);
            ObjectInputStream objectIn = new ObjectInputStream(fileIn);
	  	  Student student = (Student) objectIn.readObject();
	  	  System.out.println(student.toString());
            objectIn.close();
            System.out.println("The Object was succesfully read from the file");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}